<?php

namespace app\admin\controller;

use app\common\model\OrderData;
use think\Db;

class Order extends Common
{
    public function index()
    {
        if (request()->isPost()) {
            $key = input('post.key');
            $page = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : config('pageSize');
            $list = db('order')
                ->where('phone|sn', 'like', "%" . $key . "%")
                ->order('id desc')
                ->paginate(['list_rows' => $pageSize, 'page' => $page])
                ->toArray();
            foreach ($list['data'] as $k => $v) {
                $list['data'][$k]['create_time'] = date('Y-m-d H:s', $v['create_time']);
                if($v['px_status']==0){
                    $list['data'][$k]['order_cn'] = '待推送';
                }elseif($v['px_status']==1){
                    $list['data'][$k]['order_cn'] = '推送成功';
                }elseif($v['px_status']==2){
                    $list['data'][$k]['order_cn'] = '推送失败';
                }elseif($v['px_status']==3){
                    $list['data'][$k]['order_cn'] = '推送取消';
                }
            }
            return ['code' => 0, 'msg' => '获取成功!', 'data' => $list['data'], 'count' => $list['total']];
        }
        return $this->fetch();
    }
    
    //修改友情链接状态
    public function show(\app\common\model\Order $order, $id = 0)
    {
        $id = input('get.id');
        $rs = $order->find($id);
        if (!$rs) {
            $this->error('订单不存在');
        }

        if($rs['px_status']==0){
            $rs['order_cn'] = '待推送';
        }elseif($rs['px_status']==1){
            $rs['order_cn'] = '推送成功';
        }elseif($rs['px_status']==2){
            $rs['order_cn'] = '推送失败';
        }elseif($rs['px_status']==3){
            $rs['order_cn'] = '推送取消';
        }

        $rsd = OrderData::where('oid', $rs['id'])->select();
        $this->assign('order', $rs);
        $this->assign('order_data', $rsd);

        $wuliu_list = $this->actionTx3();
        $wuliu_list =  $wuliu_list?:[];
        $this->assign('wuliu_list', $wuliu_list);
        return $this->fetch();
    }

    //查询物流产品信息
    public function actionTx3(){
        $app_key = "44834f9e-2da8-4969-a075-68b2991e5f51";
        $app_secret = "6ac5eb06-758b-4f48-b2a7-dda078999975";
        $code = "T5YSKFM";
        $method = "com.basis.logistics_product.getlist";
        $timestamp = microtime(true);
        $timestamp = (int)(sprintf("%.3f",$timestamp) * 1000);
        $v = "1.0";
        $format = "json";
        $request_data= [
            "service_code"=>"F",                        //服务代码。4PX服务代码，可选值：F(订单履约)。
            "category_code"=>"end",               //产品分类代码。可选值：first(头程);warehouse(仓内);end(尾程)。
            "source_position_code"=>"AUMELA",
            "dest_position_code"=>"",
            "dest_country_code"=>"",
            "dest_state_name"=>"",
            "dest_city_name"=>"",
            "dest_post_code"=>""
        ];

        $data_json = json_encode($request_data);
        $str = "app_key".$app_key."format".$format."method".$method."timestamp".$timestamp."v".$v.$data_json.$app_secret;
        $sign = md5($str);
        $query_data = [
            'app_key'=>$app_key,
            'method'=>$method,
            'timestamp'=>$timestamp,
            'v'=>$v,
            'format'=>$format,
            'sign'=>$sign
        ];

        $query_str = http_build_query($query_data);
        $url = "https://open.au.4px.com/router/api/service?".$query_str;

        try{
            $httpClient = new \GuzzleHttp\Client();
            $response = $httpClient->request("post",$url,['headers'=>[],'json'=>$request_data]);
            $data = $response->getBody()->getContents();
            $data = json_decode($data,true);
//            p($data);die;
            if($data['result']==1){
                return $data['data'];
            }
            return null;
        }catch (\GuzzleHttp\Exception\RequestException $e){
            $response = $e->getResponse();
            $code=$response->getStatusCode();
            $content = $response->getBody()->getContents();
            return null;
        }
    }

    public function pxPush()
    {
        $id = input('post.id');
        $fahuo_type = input('post.fahuo_type');
        if(empty($fahuo_type)){
            $fahuo_type = "F031";
        }
        $order = Db("order")->find($id);
        if (!$order) {
            $this->error('订单不存在');
        }
        if($order['px_status']==1){
            $this->error('订单已经推送');
        }
        $goods_list = Db("order_data")->where("oid",$id)->select();
        if(empty($goods_list)){
            $this->error('订单商品不存在');
        }
        $sku_list = [];
        foreach ($goods_list as $goods){
            $sku_list[]=[
                "sku_code"=>$goods['sku'],                 //出库SKU编码
                "stock_quality"=>"G",                 //SKU库存质量。可选值：G（良好）; B（破损）; C（违禁品）; W（淋湿）; M（霉变）; E（异常）。
                "qty"=>$goods['num'],
            ];
        }

        $app_key = "44834f9e-2da8-4969-a075-68b2991e5f51";
        $app_secret = "6ac5eb06-758b-4f48-b2a7-dda078999975";

        $code = "T5YSKFM";
        $method = "fu.wms.outbound.create";
        $timestamp = microtime(true);
        $timestamp = (int)(sprintf("%.3f",$timestamp) * 1000);
        $v = "1.0";
        $format = "json";

        $request_data= [
            "ref_no"=>$order['sn'],    //客户参考号
            "from_warehouse_code"=>"AUMELA",          //出库仓库代码   澳洲墨尔本仓
            "consignment_type"=>"S",                //委托类型 S标准出库，D下架销毁，R退仓出库，O其它出库
            "logistics_service_info"=>[              //物流服务信息
                "logistics_product_code"=>$fahuo_type,         //物流产品代码 （详细参考公共服务，获取物流产品代码）
                "signature_service"=>"N",              //签名服务。 可选值：Y(选择签名服务)；N(不选择签名服务)；默认为N。
                "return_service"=>"N",                 //退件服务。 可选值：Y(选择退件服务)；N(不选择退件服务)；默认为N。
                // "customs_service"=>"N"                 //单独报关。 可选值：N(否);YRR (单独报关且退税); YNR(单独报关不退税); 默认为N
            ],
            "remark"=>"",
            "currency"=>"AUD",
            "oconsignment_desc"=>[                  //出库委托收件人信息。*注：如果国家是CN（中国），state（省）、city（市）、district（区）必须填写。其他国家state（州）或city（城市）必须填写一个。
                "country"=>"AU",
                "state"=>$order['state'],
                "city"=>$order['city'],
                "district"=>"",
                "post_code"=>$order['post_code'],           //必须
                "street"=>$order['addr1'],
                "house_number"=>"",
                "company"=>"",
                "last_name"=>$order['last_name'],           //姓
                "first_name"=>$order['first_name'],       //名
                "phone"=>$order['phone'],
                "email"=>$order['email'],
            ],
            "oconsignment_sku"=>$sku_list,
        ];
        $data_json = json_encode($request_data);
        $str = "app_key".$app_key."format".$format."method".$method."timestamp".$timestamp."v".$v.$data_json.$app_secret;
        $sign = md5($str);

        $query_data = [
            'app_key'=>$app_key,
            'method'=>$method,
            'timestamp'=>$timestamp,
            'v'=>$v,
            'format'=>$format,
            'sign'=>$sign
        ];
        $query_str = http_build_query($query_data);
        $url = "https://open.au.4px.com/router/api/service?".$query_str;

        try{
            $httpClient = new \GuzzleHttp\Client();
            $response = $httpClient->request("post",$url,['headers'=>[],'json'=>$request_data]);
            $data = $response->getBody()->getContents();
            $data = json_decode($data,true);
            //dump($data);die;
            if($data['result'] == 1){
                $px_tracking_no = $data['data']['4px_tracking_no']??"";
                $consignment_no = $data['data']['consignment_no']??"";
                Db("order")->where('id',$id)->update(['px_status'=>1,'consignment_no'=>$consignment_no,'px_tracking_no'=>$px_tracking_no]);
                $this->success('操作成功');
            }elseif($data['result'] == 0){
                $error = $data['msg']??"";
                if(isset($data['errors'][0]['error_msg'])){
                    $error = $data['errors'][0]['error_msg'];
                }
                Db("order")->where('id',$id)->update(['px_status'=>2,'px_error'=>$error]);
                $this->error($error);
            }

        }catch (\GuzzleHttp\Exception\RequestException $e){
            $response = $e->getResponse();
            $code=$response->getStatusCode();
            $content = $response->getBody()->getContents();
            $this->error($e->getMessage());
        }

        $this->success('操作成功');
    }
    
    public function listOrder()
    {
        $data = input('post.');
        if (db('links')->update($data) !== false) {
            cache('linkList', null);
            return ['msg' => '操作成功！', 'url' => url('index'), 'code' => 1];
        } else {
            return ['code' => 0, 'msg' => '操作失败！'];
        }
    }

    //订单删除
    public function listDel(){
        $order_id = $_POST['id']??0;
        $order_id = (int)$order_id;
        if($order_id<1){
            $this->error('缺少参数');
        }
        $info = Db("order")->where(['id'=>$order_id])->find();
        if(empty($info)){
            $this->error('数据不存在');
        }
        $res = Db("order")->where(['id'=>$order_id])->delete();
        if($res){
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    public function orderGoodsDel(){
        $order_goods_id = $_POST['order_goods_id']??0;
        $order_goods_id = (int)$order_goods_id;
        if($order_goods_id<1){
            $this->error('操作成功1');
        }
        $info = Db("order_data")->where(['id'=>$order_goods_id])->find();
        if(empty($info)){
            $this->error('数据不存在');
        }

        $oid = $info['oid'];
        $order = Db("order")->where(['id'=>$oid])->find();
        if(empty($order)){
            $this->error('订单数据不存在');
        }
        if($order['px_status']==1){
            $this->error('已推送订单无法修改');
        }
        $count = Db("order_data")->where("oid",$oid)->count();
        if($count==1){
            $this->error('唯一商品无法删除');
        }

        $price = sprintf("%.2f",$info['price'] * $info['num']);

        $order_total = sprintf("%.2f",$order['order_total'] - $price);
        $goods_total = sprintf("%.2f",$order['goods_total'] - $price);

        Db::startTrans();
        try{
            Db("order_data")->where('id',$order_goods_id)->delete();
            Db("order")->where(['id'=>$oid])->update(['order_total'=>$order_total,'goods_total'=>$goods_total]);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success("操作成功");
    }

    public function orderGoodsEdit(){
        $order_goods_id = $_POST['order_goods_id']??0;
        $order_goods_id = (int)$order_goods_id;
        $num = $_POST['num']??0;
        $num = (int)$num;

        if($order_goods_id<1){
            $this->error('缺少参数');
        }
        if($num<1){
            $this->error('缺少参数');
        }
        $info = Db("order_data")->where(['id'=>$order_goods_id])->find();
        if(empty($info)){
            $this->error('商品数据不存在');
        }

        $oid = $info['oid'];
        $order = Db("order")->where(['id'=>$oid])->find();
        if(empty($order)){
            $this->error('订单数据不存在');
        }
        if($order['px_status']==1){
            $this->error('已推送订单无法修改');
        }
        if($info['num'] == $num){
            $this->error('数量无改变');
        }
        $order_total = sprintf("%.2f", $num * $info['price']);
        $goods_total = sprintf("%.2f", $num * $info['price'] + $order['shipping_fee']);

        Db::startTrans();
        try{
            Db("order_data")->where('id',$order_goods_id)->update(['num'=>$num]);
            Db("order")->where(['id'=>$oid])->update(['order_total'=>$order_total,'goods_total'=>$goods_total]);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success("操作成功");
    }
    
    //添加
    public function add()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $data['create_time'] = time();
            db('links')->insert($data);
            $result['code'] = 1;
            $result['msg'] = '友情链接添加成功!';
            $result['url'] = url('index');
            cache('linkList', null);
            return $result;
        } else {
            $this->assign('title', lang('add') . lang('link'));
            $this->assign('info', 'null');
            return $this->fetch('edit');
        }
    }
    
    //修改友情链接
    public function edit()
    {
        if (request()->isPost()) {
            $data = input('post.');
            db('links')->update($data);
            $result['code'] = 1;
            $result['msg'] = '友情链接修改成功!';
            $result['url'] = url('index');
            cache('linkList', null);
            return $result;
        } else {
            $id = input('param.id');
            $info = db('links')->where(['id' => $id])->find();
            $this->assign('info', $info);
            $this->assign('title', lang('edit') . lang('link'));
            return $this->fetch('edit');
        }
    }
    
    public function del()
    {
        db('links')->where(['id' => input('id')])->delete();
        cache('linkList', null);
        return ['code' => 1, 'msg' => '删除成功！'];
    }
    
    public function delall()
    {
        $map[] = ['id', 'IN', input('param.ids/a')];
        db('links')->where($map)->delete();
        $result['msg'] = '删除成功！';
        $result['code'] = 1;
        $result['url'] = url('index');
        cache('linkList', null);
        return $result;
    }
}